package cn.ittest.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/*
工具类实现：
1.私有化构造方法：不让外界对此类进行创建对象。
2.声明的方法都是静态的。
3.声明的变量都是私有的。
* */
public class JDBCUtil {

    private JDBCUtil(){}
    private static String driver ;
    private static String url;
    private static String username;
    private static String pwd;
    private static Connection con;
    static{
        try {
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db1.properties");
            Properties pro = new Properties();
            pro.load(is);
            driver = pro.getProperty("driver");
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            pwd = pro.getProperty("pwd");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        try {
            con = DriverManager.getConnection(url, username, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
         return con;
    }
    public static void close(Connection con, Statement stat, ResultSet rs){
        if(con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection con, Statement stat){
        if(con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
